package com.doubao.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doubao.entity.SmartDevice;
import com.doubao.entity.vo.SmartDeviceVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;

@Mapper
public interface SmartDeviceMapper extends BaseMapper<SmartDevice> {

    @Select({
            "<script>",
            "SELECT d.id, d.user_id, d.name, d.icon, d.description, d.visibility, d.type,",
            "d.category, d.collect_count, d.chat_count, d.created_at, d.model_endpoint_id, d.system_prompt,",
            "u.username as creator_name,",
            "(SELECT COUNT(1) > 0 FROM user_device_collection c",
            "WHERE c.device_id = d.id AND c.user_id = #{userId} AND c.status = 1) as is_collected",
            "FROM smart_device d",
            "LEFT JOIN user u ON u.id = d.user_id",
            "WHERE d.visibility = 1",  // 只查询公开的智能体
            "AND d.deleted = 0",       // 未删除的
            "<when test='category != null and category != \"\"'>",
            "AND d.category = #{category}",
            "</when>",
            "ORDER BY d.collect_count DESC, d.created_at DESC",
            "</script>"
    })
    IPage<SmartDeviceVO> selectPublicDevices(
            Page<SmartDevice> page,
            @Param("userId") Long userId,
            @Param("category") String category
    );

    @Select({
            "SELECT d.id, d.user_id, d.name, d.icon, d.description, d.visibility, d.type,",
            "d.category, d.collect_count, d.chat_count, d.created_at, d.model_endpoint_id, d.system_prompt,",
            "u.username as creator_name,",
            "(SELECT COUNT(1) > 0 FROM user_device_collection c",
            "WHERE c.device_id = d.id AND c.user_id = #{userId} AND c.status = 1) as is_collected",
            "FROM smart_device d",
            "LEFT JOIN user u ON u.id = d.user_id",
            "WHERE d.user_id = #{userId}",
            "OR EXISTS (",
            "  SELECT 1 FROM user_device_collection c",
            "  WHERE c.device_id = d.id AND c.user_id = #{userId} AND c.status = 1",
            ")",
            "AND d.deleted = 0",
            "ORDER BY d.created_at DESC"
    })
    List<SmartDeviceVO> selectUserDevices(@Param("userId") Long userId);

}
